package org.tcx.web.ajax;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorException;
import org.tcx.common.LogUtil;

public final class Action {
	private static Log log = LogFactory.getLog(Action.class);
	private final String path;
	private final String method;
	private final Class<?> claz;
	private final Validator validator;

	public String getPath() {
		return path;
	}

	public String getMethod() {
		return method;
	}

	public Class<?> getClaz() {
		return claz;
	}

	public Action(String path, String method, Class<?> claz,
			Validator validator) {
		this.path = path;
		this.method = method;
		this.claz = claz;
		this.validator = validator;
	}

	public Object invoke(JSON json, HttpServletRequest req,
			HttpServletResponse resp) throws ClassNotFoundException,
			SecurityException, NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			InstantiationException, ValidatorException {
		log.debug("enter" + LogUtil.arg("json, req, resp", json, req, resp));
		validator.setParameter(Validator.BEAN_PARAM, json);
		validator.validate();

		Method actionMethod = claz.getDeclaredMethod(method, JSON.class,
				HttpServletRequest.class, HttpServletResponse.class);
		Object result = actionMethod
				.invoke(claz.newInstance(), json, req, resp);
		log.debug(LogUtil.arg("result", result));
		log.debug("leave");
		return result;
	}
}
